package com.itfreer.data.general;

import com.itfreer.data.general.utils.ValueConvertUtils;
import com.itfreer.utils.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * 类功能说明 定义记录行实体基类
 */
public class RowBase extends HashMap<String, Object> implements Cloneable, Serializable {

	private static final long serialVersionUID = -2265886069121726414L;

	/**
	 * 定义表的唯一值字段
	 */
	public final static String FIELD_GUID = "GUID";

	/**
	 * 定义表的版本号字段
	 */
	public final static String FIELD_VERSION = "I_VERSION";
	/**
	 * 获取或设置子表对象
	 */
	private HashMap<String, List<RowBase>> childValues;

	public RowBase() {
		setIsNew(true);
	}

	/**
	 * 获取当前列
	 */
	public String[] getColumns() {
		List<String> keys = new ArrayList<String>();
		keys.addAll(this.keySet());
		return keys.toArray(new String[keys.size()]);
	}

	/**
	 * 获取子表记录
	 * 
	 * @return
	 */
	public HashMap<String, List<RowBase>> getChildValues() {
		return this.childValues;
	}

	/**
	 * 设置子表记录
	 * 
	 * @param value
	 */
	public void setChildValues(HashMap<String, List<RowBase>> value) {
		this.childValues = value;
	}

	/**
	 * 获取字段值
	 */
	public Object getValue(GlobalDataType globalDataType, String fieldName) {
		Object obj = getValue(fieldName);
		return ValueConvertUtils.ConvertValue(globalDataType, null, obj);
	}

	/**
	 * 获取或设置字段值
	 */
	public Object getValue(String fieldName) {
		if (StringUtils.IsNullOrSpace(fieldName))
			return null;

		String key = fieldName.toUpperCase().trim();
		return this.get(key);
	}

	/**
	 * 设置字段值
	 */
	public void setValue(String fieldName, Object obj) {
		if (StringUtils.IsNullOrSpace(fieldName))
			return;
		String key = fieldName.toUpperCase().trim();
		this.put(key, obj);
	}

	public static String FIELD_ISNEW = "FIELD_ISNEW";

	/**
	 * 获取当前实现是否为新对象
	 * 
	 * @return
	 */
	public boolean getIsNew() {
		boolean result = (Boolean) getValue(GlobalDataType.Boolean, FIELD_ISNEW);
		return result;
	}

	/**
	 * 设置对象是否为新对象
	 * 
	 * @param value
	 */
	public void setIsNew(boolean value) {
		setValue(FIELD_ISNEW, value);
	}

	/**
	 * 是否为系统字段
	 */
	public static boolean isSystemField(String fieldName) {
		if (StringUtils.IsNullOrSpace(fieldName))
			return false;

		fieldName = fieldName.toUpperCase().trim();

		if (fieldName.equals(FIELD_VERSION) || fieldName.equals(FIELD_GUID))
			return true;
		else
			return false;
	}

	/**
	 * 获取值缓存数据的key
	 * 
	 * @return
	 */
	public String getKey() {
		String keyString = "";
		Set<String> keys = this.keySet();
		for (String key : keys) {
			if (get(key) == null) {
				keyString += key + "_null_";
			} else {
				keyString += key + "_" + get(key) + "_";
			}
		}
		return keyString;
	}
}